'use strict';
app.controller('contractListCtl', function($scope, $http, rest, $compile, $location, ngDialog, user, $state, $window, uiLoad, $rootScope, $ocLazyLoad) {
    var token = $window.localStorage.getItem("token");

    //方法级权限
    var accessStr = $window.localStorage.getItem("accessStr");
    $scope.btns = {
            add: 'innjia', //新建
            delete: 'innjia', //删除
            edit: 'innjia', //编辑
            jurisdiction: 'innjia', //权限分配
            resetPasswords: 'innjia', //重置密码
            addmember: 'innjia', //添加成员
            exportExcel: 'innjia', //导出表格
            batchExportImg: 'innjia', //批量导出图片
            details: 'innjia', //详情
            rent: 'innjia', //租赁PDF
            list: 'innjia', //列表
            batchApproval: 'innjia', //批量审批
            batchClaim: 'innjia' //批量认领
        }
        //延迟执行 - 当左侧菜单生产完毕再获取当前菜单的ID 利用ui-sref-active有且只有一个active即当前的特性用jq去获取预先存储在菜单上的id
    user.response().then(function(res) {
        var nowId = $(document).find(".navItem.active").attr("data-id");
        rest.decoJava({
            type: "post",
            url: "/tenancy-sys/admin/menu/detail/" + nowId,
            data: "",
            //contentType:"application/json",
            beforeSend: function(request) {
                request.setRequestHeader("token", token);
            },
            success: function(data) {
                console.log(data)
                if (data.code == "0000") {
                    //匹配权限
                    angular.forEach(data.result.menuMethods, function(data) {
                        if (data.methodTagName == "add") {
                            $scope.btns.add = data.id;
                        } else if (data.methodTagName == "delete") {
                            $scope.btns.delete = data.id;
                        } else if (data.methodTagName == "edit") {
                            $scope.btns.edit = data.id;
                        } else if (data.methodTagName == "jurisdiction") {
                            $scope.btns.jurisdiction = data.id;
                        } else if (data.methodTagName == "resetPasswords") {
                            $scope.btns.resetPasswords = data.id;
                        } else if (data.methodTagName == "addmember") {
                            $scope.btns.addmember = data.id;
                        } else if (data.methodTagName == "exportExcel") {
                            $scope.btns.exportExcel = data.id;
                        } else if (data.methodTagName == "batchExportImg") {
                            $scope.btns.batchExportImg = data.id;
                        } else if (data.methodTagName == "details") {
                            $scope.btns.details = data.id;
                        } else if (data.methodTagName == "rent") {
                            $scope.btns.rent = data.id;
                        } else if (data.methodTagName == "list") {
                            $scope.btns.list = data.id;
                        } else if (data.methodTagName == "batchApproval") {
                            $scope.btns.batchApproval = data.id;
                        } else if (data.methodTagName == "batchClaim") {
                            $scope.btns.batchClaim = data.id;
                        }
                    })
                } else if (data.message == "菜单Id有误！！！") {
                    // $window.location.reload();
                } else {
                    layer.msg(data.message + '请刷新试试', {
                        offset: 't',
                        icon: 2
                    });
                }
            }
        });

    })

    //合同状态
    $scope.contractStatusList = [{
        "key": "",
        "name": "请选择合同状态"
    }, {
        "key": "EXPIRED",
        "name": "已失效"
    }, {
        "key": "WAITAFFIRM",
        "name": "待确认"
    }, {
        "key": "CONFIRMED",
        "name": "已确认"
    }];
    $scope.contractStatus = $scope.contractStatusList[0];

    //首付状态
    $scope.downPaymentStatusList = [{
        "key": "",
        "name": "请选择首付状态"
    }, {
        "key": "UNPAID",
        "name": "未支付"
    }, {
        "key": "PAID",
        "name": "已支付"
    }]
    $scope.downPaymentStatus = $scope.downPaymentStatusList[0];

    var tabHeight = ($window.innerHeight - 356) + "px"; //table内容区高度
    $scope.dataTableSettingContracts = {
        "sAjaxSource": "/tenancy-sys/contract-resource/contracts/query",
        // "dom": "tipr",
        "bFilter": true, //搜索
     	"sScrollY": tabHeight,  //给定高度，内容超出即出滚动条
     	"bScrollCollapse": false,  //不管内容多少高度固定
        "aLengthMenu": [25, 50, 100, 200],
        "iDisplayLength": 25,
        "sDom": '<"top">rt<"bottom"lip><"clear">', //位置 l-每页显示数量,f-过滤输入,t-表单Table,i-信息,p-翻页
        // "bAutoWidth": true, //自适应列宽
        "aoColumns": [{
            "mDataProp": "",
            "sDefaultContent": "",
            "sClass": "center handle-ck"
        }, {
            "mDataProp": "communityName",
            "sTitle": "小区名称",
            "sDefaultContent": "",
            "sClass": "center failure"
        }, {
            "mDataProp": "detailedAddress",
            "sTitle": "详细地址",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "landlordName",
            "sTitle": "房东姓名",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "landlordPhone",
            "sTitle": "房东手机",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "tenantName",
            "sTitle": "租客姓名",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "tenantPhone",
            "sTitle": "租客手机",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "totalAmount",
            "sTitle": "租金(元)",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "paymentType",
            "sTitle": "支付方式",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "rentDay",
            "sTitle": "交租日",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "",
            "sTitle": "租期",
            "sDefaultContent": "",
            "sClass": "center leaseBar"
        }, {
            "mDataProp": "",
            "sTitle": "首付款状态",
            "sDefaultContent": "",
            "sClass": "center handle-sfzt"
        }, {
            "mDataProp": "validRentDay",
            "sTitle": "已付期数",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "updateTime",
            "sTitle": "合同确认时间",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "",
            "sTitle": "合同状态",
            "sDefaultContent": "",
            "sClass": "center handle-htzt"
        }, {
            "mDataProp": "",
            "sTitle": "操作",
            "sDefaultContent": "",
            "sClass": "center handle-td"
        }],
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {

            if (aData.downPaymentStatus == "PAID") {
                $(nRow).find(".handle-sfzt").append("已支付");
            } else if (aData.downPaymentStatus == "UNPAID") {
                $(nRow).find(".handle-sfzt").append("未支付");
            }

            //操作按钮
            var btnStr = "";
            if (aData.contractStatus == "WAITAFFIRM") {
                $(nRow).find(".handle-htzt").append("待确认");
                //<a ng-click="editContract('+iDisplayIndex+',$even)" style="margin:0;" href="javascript:;">修改合同</a>
                //<dd><a href='javascript:' ng-click='openRentDetails(\"" + iDisplayIndex + "\",$even)'>查看租赁合同</a></dd>\
                btnStr += " <a class='operation-btn'>\
                    <img src='img/operation.png' width='20px' height='20px' />\
                    <div class='operation-none' >\
                        <dl class='operation oper-triangle'>\
                            <dd><a href='javascript:' data-btn='btns.details' ng-click='openDetails(\"" + iDisplayIndex + "\",$even)'>查看合同详情</a></dd>\
                            <span class='z'>▲</span><span class='y'>▲</span>\
                        </dl>\
                    </div>\
                </a>";
            } else if (aData.contractStatus == "EXPIRED") {
                $(nRow).find(".handle-htzt").append("已失效");
                btnStr += " <a class='operation-btn'>\
                    <img src='img/operation.png' width='20px' height='20px' />\
                    <div class='operation-none' >\
                        <dl class='operation oper-triangle'>\
                            <dd><a href='javascript:' data-btn='btns.details' ng-click='openDetails(\"" + iDisplayIndex + "\",$even)'>查看合同详情</a></dd>\
                            <dd><a href='javascript:' data=btn='btns.rent' ng-click='openPdf(\"" + iDisplayIndex + "\",$even)'>查看PDF</a></dd>\
                            <span class='z'>▲</span><span class='y'>▲</span>\
                        </dl>\
                    </div>\
                </a>";
            } else if (aData.contractStatus == "CONFIRMED") {
                $(nRow).find(".handle-htzt").append("已确认");
                btnStr += " <a class='operation-btn'>\
                    <img src='img/operation.png' width='20px' height='20px' />\
                    <div class='operation-none' >\
                        <dl class='operation oper-triangle'>\
                            <dd><a href='javascript:' data-btn='btns.details' ng-click='openDetails(\"" + iDisplayIndex + "\",$even)'>查看合同详情</a></dd>\
                            <dd><a href='javascript:' data=btn='btns.rent' ng-click='openPdf(\"" + iDisplayIndex + "\",$even)'>查看PDF</a></dd>\
                            <span class='z'>▲</span><span class='y'>▲</span>\
                        </dl>\
                    </div>\
                </a>";
            }

            $(nRow).find(".handle-td").append($compile(btnStr)($scope));

            /*$(nRow).find(".operation-btn").on('click', function(ev) {
            	ev.stopPropagation();
            	
            	var sopt = $(this).parent().find(".operation-none");
            	
                if (sopt.css('display') == 'none') {
                    sopt.show();
                    $scope.isCoverBgShow = true;
                    $scope.$apply();
                } else {
                    sopt.hide();
                    $scope.isCoverBgShow = false;
                    $scope.$apply();
                }
            });*/

            //插入租期时间段
            var leaseStr = "";
            leaseStr += aData.leaseStartTime + "—" + aData.leaseEndTime;
            $(nRow).find(".leaseBar").append(leaseStr);

            //插入checkbox复选框
            var checkStr = "";
            checkStr += '<input type="checkbox" data-index="' + iDisplayIndex + '" value="' + $scope.myDatas.result[iDisplayIndex].id + '" class="checkchild" />';
            $(nRow).find(".handle-ck").append($compile(checkStr)($scope));

            //菜单等级
            var gradeStr = "";
            if (aData.level == 0) {
                gradeStr = "一级角色";
            } else {
                gradeStr = "二级角色";
            }
            $(nRow).find(".menu-grade").append(gradeStr);

            //菜单状态
            var menuStatus = "";
            if (aData.status == "AVAILABLE") {
                menuStatus = "可用";
            } else if (aData.status == "DELETE") {
                menuStatus = "删除";
            } else if (aData.status == "FORBID") {
                menuStatus = "禁止";
            }
            $(nRow).find(".menuStatus").append(menuStatus);
        },
        "fnDrawCallback": function(oSettings) {

        },
        "fnServerParams": function(aoData) {

        },
        "fnServerData": function(sSource, aData, fnCallback, dataTableObject) {
            //$scope.upRole 可能为null 所以要做下判断处理 避免报错
            var upRoleId = null;
            if ($scope.upRole != null) {
                upRoleId = $scope.upRole.id
            }

            //数字判断函数，返回true表示是全部数字，返回false表示不全部是数字 
            function isNumber(str) {
                if ("" == str) {
                    return false;
                }
                var reg = /\D/;
                return str.match(reg) == null;
            }
            //租客
            if ($scope.tenant == undefined || $scope.tenant == "") {
                $scope.tenantName = "";
                $scope.tenantPhone = "";
            } else {
                if (isNumber($scope.tenant)) {
                    $scope.tenantPhone = $scope.tenant; //手机号
                    $scope.tenantName = "";
                } else {
                    $scope.tenantPhone = "";
                    $scope.tenantName = $scope.tenant; //姓名
                }
            }
            //房东
            if ($scope.landlord == undefined || $scope.landlord == "") {
                $scope.landlordName = "";
                $scope.landlordPhone = "";
            } else {
                if (isNumber($scope.landlord)) {
                    $scope.landlordPhone = $scope.landlord; //手机号
                    $scope.landlordName = "";
                } else {
                    $scope.landlordPhone = "";
                    $scope.landlordName = $scope.landlord; //姓名
                }
            }

            var obj = dataTableObject.oAjaxData,
                _baseParams = {
                    // 'landlordId':user.get('landlordId'),
                    'page': obj.iDisplayStart / obj.iDisplayLength + 1,
                    'rows': obj.iDisplayLength,
                    'search': 'false',
                    'nd': '1494221804416',
                    // 'rows': 50,
                    // 'page': 1,
                    'order': "asc",
                    //"roleName": $scope.userName,  //搜索参数 menuName：菜单搜索  tagName：关键字搜索
                    //"upId": upRoleId,
                    //"status": $scope.itemStatus.status
                    communityName: $scope.communityName, //小区名称
                    tenantName: $scope.tenantName, //租客姓名
                    tenantPhone: $scope.tenantPhone, //租客手机号
                    landlordName: $scope.landlordName, //房东姓名
                    landlordPhone: $scope.landlordPhone, //房东手机
                    contractStatus: $scope.contractStatus.key, //合同状态
                    downPaymentStatus: $scope.downPaymentStatus.key //首付状态
                        //checkStatus: ''
                };
            var __data = angular.extend({}, _baseParams, obj.queryParams);
            rest.decoJava({
                    type: 'post',
                    url: sSource,
                    data: __data,
                    beforeSend: function(request) {
                        request.setRequestHeader("token", token);
                    },
                    success: function(data) {
                        console.log(data);
                        $scope.myDatas = data;
                        var data1 = {
                            'aaData': data.result,
                            'sEcho': obj.sEcho,
                            'iTotalDisplayRecords': data.pager.recordCount,
                            'iTotalRecords': data.records
                        };
                        fnCallback(data1);
                        /*$(".dataTables_scrollHead").css("overflow","visible");
                        $(".dataTables_scrollBody").css('height','100%');
                        $(dataTableObject.nScrollBody).css('overflow', 'visible');
                        $(dataTableObject.nScrollBody).css('margin-bottom', 60 + 'px');*/
                       	$(".dataTables_scroll").css("overflow", "auto");
        				$(".dataTables_scrollBody").css("overflow", "visible");
        				$(".dataTables_scrollBody table").css("marginBottom", "60px");
                        
                    }
                })
                //搜索 说明 只要是点击的搜索就让page为1 并且刷新datatables目的是回到第一页
                //说明 自定义搜索只需在点击搜索的时候改变下datatables传过去的参数 然后$scope.dataTable.fnClearTable()即可
            $scope.search = function() {
                __data.page = 1;
                $scope.dataTable.fnClearTable();
            }
        }
    }

    $scope.initFinishContractList = function(dataTable) {
        $scope.dataTable = dataTable;
    }
    $(document).on("click", ".operation-btn", function(ev) {
        ev.stopPropagation();
        $(".operation-none").hide();
        var that = $(this).siblings(".operation-none");
        if (that.css("display") == "none") {
            that.show();
        } else {
            that.hide();
        }
    })
    $(document).on("click", function() {
            $(".operation-none").hide();
        })
        /*$scope.coverBgHide = function() {
            $('.operation-none').hide();
            $scope.isCoverBgShow = false;
            //$scope.$apply();
        } */
        //操作
        /* $(document).on("click",".dropdownBar",function(ev){
         	ev.stopPropagation();
         	$(".dropdownBar").removeClass("open");
         	$(this).addClass("open");
         })
         $(document).on("click",function(){
         	$('.operation-none').hide();
         })*/

    //修改合同
    $scope.editContract = function(iDisplayIndex, e) {

        /*//权限控制
    	var nowId = this.btns.bj;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}*/

        ngDialog.openConfirm({
            template: 'js/module/decorate/editContract.html',
            resolve: {
                load: function() {
                    return $ocLazyLoad.load('angularFileUpload').then(
                        function() {
                            return uiLoad.load(['js/module/decorate/editContract.js'])
                        });
                }
            },
            data: $scope.myDatas.result[iDisplayIndex],
            scope: $scope,
            width: 1200,
            // height: 700
        }).then(function(data) {
            $scope.dataTable.fnClearTable();
        }, function(reason) {
            $scope.dataTable.fnClearTable();
        });

    }

    //查看pdf
    $scope.openPdf = function(iDisplayIndex, e) {
        //权限控制
        var nowId = this.btns.rent;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        ngDialog.openConfirm({
            template: 'js/module/decorate/contractPDF.html',
            resolve: {
                load: function() {
                    return $ocLazyLoad.load('angularFileUpload').then(
                        function() {
                            return uiLoad.load(['js/module/decorate/contractPDF.js'])
                        });
                }
            },
            data: $scope.myDatas.result[iDisplayIndex],
            scope: $scope,
            width: 1200,
            // height: 700
        }).then(function(data) {
            $scope.dataTable.fnClearTable();
        }, function(reason) {
            $scope.dataTable.fnClearTable();
        });
    }

    //导出excel
    $scope.exportExcel = function() {
        //权限控制
        var nowId = this.btns.exportExcel;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        if ($(".checkchild:checked").length == 0) {
            layer.msg("没有选中项", {
                offset: 't',
                icon: 2,
                time: 2000
            });
        } else {

            //选中的数据id
            var idArr = [];
            $(".checkchild").each(function() {
                if ($(this).is(":checked")) {
                    idArr.push($(this).val());
                }
            });
            var _idstring = "";
            angular.forEach(idArr, function(data) {
                _idstring += data + ',';
            })
            var _idstring = _idstring.substring(0, _idstring.length - 1);

            ngDialog.openConfirm({
                template: 'js/module/decorate/exportExcel.html',
                resolve: {
                    load: function() {
                        return $ocLazyLoad.load('angularFileUpload').then(
                            function() {
                                return uiLoad.load(['js/module/decorate/exportExcel.js'])
                            });
                    }
                },
                data: {
                    _idstring: _idstring
                },
                scope: $scope,
                width: 1200,
                // height: 700
            }).then(function(data) {
                $scope.dataTable.fnClearTable();
            }, function(reason) {
                $scope.dataTable.fnClearTable();
            });
        }
    }

    //查看合同详情
    $scope.openDetails = function(iDisplayIndex, e) {
        //权限控制
        var nowId = this.btns.details;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        ngDialog.openConfirm({
            template: 'js/module/decorate/contractDetails.html',
            resolve: {
                load: function() {
                    return $ocLazyLoad.load('angularFileUpload').then(
                        function() {
                            return uiLoad.load(['js/module/decorate/contractDetails.js'])
                        });
                }
            },
            data: $scope.myDatas.result[iDisplayIndex],
            scope: $scope,
            width: 1200,
            // height: 700
        }).then(function(data) {
            $scope.dataTable.fnClearTable();
            $scope.isCoverBgShow = false;
        }, function(reason) {
            $scope.dataTable.fnClearTable();
            $scope.isCoverBgShow = false;
        });
    }

    //查看租赁合同
    $scope.openRentDetails = function(iDisplayIndex, e) {
        ngDialog.openConfirm({
            template: 'js/module/decorate/rentDetails.html',
            resolve: {
                load: function() {
                    return $ocLazyLoad.load('angularFileUpload').then(
                        function() {
                            return uiLoad.load(['js/module/decorate/rentDetails.js'])
                        });
                }
            },
            data: $scope.myDatas.result[iDisplayIndex],
            scope: $scope,
            width: 1200,
            // height: 700
        }).then(function(data) {
            $scope.dataTable.fnClearTable();
            $scope.isCoverBgShow = false;
        }, function(reason) {
            $scope.dataTable.fnClearTable();
            $scope.isCoverBgShow = false;
        });
    }

    //重置
    $scope.reset = function() {
        $scope.communityName = "";
        $scope.tenant = "";
        $scope.landlord = "";
        $scope.contractStatus = $scope.contractStatusList[0];
        $scope.downPaymentStatus = $scope.downPaymentStatusList[0];
        $scope.dataTable.fnClearTable();
    }

    //全部选中和取消
    $scope.allMenu = function(e) {
        var This = angular.element(e.target);
        if (This.is(":checked")) {
            angular.element(".checkchild").prop("checked", true);
        } else {
            angular.element(".checkchild").prop("checked", false);
        }
    }



});